#pragma once
#include <iostream>
#include "../Comm/Httplib.hpp"
#include "../Comm/Log.hpp"
#include "../Comm/Util.hpp"
#include "model.hpp"
#include "view.hpp"
#include <mutex>
#include <assert.h>
#include <jsoncpp/json/json.h>


namespace ns_control
{
    using namespace httplib;
    using namespace ns_log;
    using namespace ns_util;
    using namespace ns_model;
    using namespace ns_view;

    class Machine
    {
    public:
        std::string ip;
        int port;
        uint64_t load;
        std::mutex* mtx;

        Machine()
        :ip(""),port(0),load(0),mtx(nullptr)
        {}
        ~Machine(){}

        void IncLoad()
        {
            if(mtx) mtx->lock();// 确保该锁存在
            load++;
            if(mtx) mtx->unlock();
        }
        void DecLoad()
        {
            if(mtx) mtx->lock();
            load--;
            if(mtx) mtx->unlock();
        }

        void Clear()
        {
            if(mtx) mtx->lock();
            load = 0;
            if(mtx) mtx->unlock();
        }
        
    };

    const std::string conf_path = "./conf/server_machine.conf";

    class LoadBalace
    {
    private:
        std::vector<Machine> machines;
        std::vector<int> onlines;
        std::vector<int> offlines;
        std::mutex mtx;
    public:
        LoadBalace()
        {
            LoadConf(conf_path);
            LOG(INFO) << "加载配置文件成功" << "\n";
        }
        ~LoadBalace(){}

        bool LoadConf(const std::string& server_conf)
        {
            std::ifstream in(server_conf);
            if(!in.is_open())
            {
                LOG(ERROR) << "加载配置文件失败" << "\n";
                return false;
            }
            std::string line;
            while(getline(in, line))
            {
                std::vector<std::string> tokens;
                StringUtil::splitString(line, &tokens, " ");
                Machine m;
                m.ip = tokens[0];
                m.port = std::atoi(tokens[1].c_str());
                m.load = 0;
                m.mtx = new std::mutex();
                
                onlines.push_back(machines.size());
                machines.push_back(m);
            }

            in.close();
            return true;
        }
        bool StartChoice(int* id, Machine** m)
        {
            mtx.lock();
            int online_num = onlines.size();
            if(online_num == 0)
            {
                mtx.unlock();
                LOG(ERROR) << "没有编译运行服务启动，需要检查一下" << "\n";
                return false;
            }
            uint64_t min_load = machines[onlines[0]].load;
            *id = onlines[0];//!!!
            *m = &machines[onlines[0]];
            for(int i=0; i<online_num; i++)
            {
                uint64_t cur_load = machines[onlines[i]].load;
                if(cur_load < min_load)
                {
                    min_load = cur_load;
                    *id = onlines[i];// ！！！！
                    *m = &machines[onlines[i]];
                }
            }
            mtx.unlock();
            return true;
        }
        void Offlines(int id)
        {
            mtx.lock();
            for(auto iter=onlines.begin(); iter != onlines.end(); iter++)
            {
                if(*iter == id)
                {
                    machines[id].Clear();// 离线的主机负载清0

                    onlines.erase(iter);
                    offlines.push_back(id);
                    break;// 没有break可能导致迭代器失效!!!
                }
            }
            mtx.unlock();
        }
        void ShowMachines()
        {
            mtx.lock();
            std::cout << "在线的主机id: ";
            for(auto& e : onlines)
            {
                std::cout << e << " ";
            }
            std::cout << std::endl;
            std::cout << "离线的主机id: ";
            for(auto& e : offlines)
            {
                std::cout << e << " ";
            }
            std::cout << std::endl;
            mtx.unlock();
        }
        void Onlines()
        {
            mtx.lock();
            // 统一上线
            onlines.insert(onlines.end(), offlines.begin(), offlines.end());
            offlines.erase(offlines.begin(), offlines.end());
            mtx.unlock();
        }
    };

    class Control
    {
    private:
        Model model;
        View view;
        LoadBalace load_balance;
    public:
        Control(){}
        ~Control(){}
        void Recover()
        {
            load_balance.Onlines();
            LOG(INFO) << "所有主机都要上线了..." << "\n";
        }
        bool AllQuestions(std::string* html)
        {
            std::vector<Question> all;
            if(model.getAllQuestions(&all))
            {
                view.AllExpandHtml(all, html);
            }   
            else 
            {
                LOG(ERROR) << "获取题库失败" << "\n";
                return false;
            }
            return true;
        }

        bool OneQuestion(const std::string& number, std::string* html)
        {
            Question q;
            if(model.getOneQuestion(number, &q))
            {
                view.OneRxpandHtml(q, html);
            }
            else 
            {
                LOG(ERROR) << "获取指定题目失败" << "\n";
                return false;
            }
            return true;
        }
        
        void Judge(const std::string& number, const std::string& in_json, std::string* out_json)
        {
            Question q;
            model.getOneQuestion(number, &q);

            Json::Value in_value;
            Json::Reader reader;
            reader.parse(in_json, in_value);
            std::string code = in_value["code"].asString();

            Json::Value compile;
            compile["input"] = in_value["input"].asString();
            compile["code"] = code + "\n" + q.tail;
            compile["cpu_limit"] = q.cpu_limit;
            compile["mem_limit"] = q.mem_limit;
            Json::FastWriter writer;
            std::string compile_string = writer.write(compile);

            while(true)
            {
                int id = 0;
                Machine* m = nullptr;
                if(!load_balance.StartChoice(&id, &m))
                {
                    break;
                }
                LOG(INFO) << "选择主机成功, id: " << id << ", ip: " << m->ip << ", port: " << m->port << ", 负载: " << m->load << "\n";
                Client cli(m->ip, m->port);
                m->IncLoad();
                if(auto res = cli.Post("/compile_run", compile_string, "application/json;charset=utf-8"))
                {
                    if(res->status == 200)
                    {
                        m->DecLoad();
                        *out_json = res->body;
                        LOG(INFO) << "编译和运行服务成功执行..." << "\n";
                        break;
                    }
                }
                else 
                {
                    LOG(ERROR) << "请求主机失败, id: " << id << ", ip: " << m->ip << ", port: " << m->port << ", 负载: " << m->load << "\n";
                    load_balance.Offlines(id);
                    load_balance.ShowMachines();
                }
            }
        }
    };
}